var gulp = require('gulp');
var plugins = require('gulp-load-plugins')(),
    uglify = require('gulp-uglify'), // js压缩
    cleanCss = require("gulp-clean-css"), // css压缩
    imagemin = require('gulp-imagemin'), // 图片压缩
    pngquant = require('imagemin-pngquant'), // png图片压缩插件
    rev = require('gulp-rev'), // 文件版本号控制
    revCollector = require('gulp-rev-collector'), // 文件名替换
    replace = require('gulp-replace'), // 文件名替换
    htmlmin = require('gulp-htmlmin'), // html压缩
    clean = require('gulp-clean'), // 清空文件夹，避免文件冗余
    copy = require('gulp-copy'), // 复制
    fileInclude = require('gulp-file-include'), // 文件引用
    runSequence = require('run-sequence'), // 执行顺序，避免
    watch = require('gulp-watch'),
    livereload = require('gulp-livereload'),
    sftp = require('gulp-sftp');
    var gutil = require('gulp-util');
//dist
gulp.task('dist', function() {
    runSequence(
        'clean-dist', ['minify-js-rev', 'minify-css'],
        'file-include',
        'del-widget',
        'minify-html',
        'copy-fonts',
        'copy-editor',
        'clean-temp',
        'img-minify',
        'build',
        'clean-json'
    );
});
//watch
gulp.task('watch', function() {
    return gulp.watch(['./src/template/*.html','./src/js/*.js'], function(event) {
        if (event.type == 'changed') {
            runSequence(
              'file-include',
              'del-widget',
              'check-js'
            );
            livereload.listen();
        };
    });
});

gulp.task('clean-dist', function() {
    return gulp.src(['./dist', './temp', './json'])
        .pipe(clean());
});
gulp.task('clean-cache', function() {
    return gulp.src('./cache')
        .pipe(clean());
});
gulp.task('minify-js', function() {
    return gulp.src(['./src/js/*.js','./src/js/**/*.js','./src/js/**/**/*.js', '!./src/js/**/*.min.js', '!./src/js/**/**/*.min.js', '!./src/ueditor/*'], { base: './src/js' }) // 要压缩的js文件
        .pipe(uglify({
            mangle: true,//类型：Boolean 默认：true 是否修改变量名
            compress: true,//类型：Boolean 默认：true 是否完全压缩
        }))
        .on('error', function (err) {
            gutil.log(gutil.colors.red('[Error]'), err.toString());
        })
        .pipe(gulp.dest('./temp/js'));
});
gulp.task('check-js', function() {
  return gulp.src(['./src/js/*.js','./src/js/**/*.js','./src/js/**/**/*.js', '!./src/js/**/*.min.js', '!./src/js/**/**/*.min.js', '!./src/ueditor/*'], { base: './src/js' }) // 要压缩的js文件
    .on('error', function (err) {
      gutil.log(gutil.colors.red('[Error]'), err.toString());
    });
});
gulp.task('copy-minJs', function() {
    return gulp.src(['./src/js/**/*.min.js','./src/js/**/**/*.min.js', '!./src/ueditor/*', './src/ueditor/ueditor.config.js', './src/ueditor/ueditor.all.js'], { base: './temp/js' })
        .pipe(copy('./temp/', {
            prefix: 1
        }));
});
gulp.task('minify-js-rev', ['copy-minJs', 'minify-js'], function() {
    return gulp.src(['./temp/js/*.js', './temp/js/**/*.js', './temp/js/**/**/*.js', './temp/js/**/*.min.js', '!./temp/ueditor/*', './src/ueditor/ueditor.config.js', './src/ueditor/ueditor.all.js' ], { base: './temp/js' }) // 要压缩的js文件
        .pipe(rev())
        .pipe(gulp.dest('./dist/js'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./json/js')); //压缩后的路径
});
gulp.task('minify-css', function() {
    return gulp.src(['./src/css/*.css','./src/css/**/*.css', '!./src/ueditor/*']) // 要压缩的css文件
        .pipe(cleanCss({
            advanced: false, //类型：Boolean 默认：true [是否开启高级优化（合并选择器等）]
            compatibility: 'ie7', //保留ie7及以下兼容写法 类型：String 默认：''or'*' [启用兼容模式； 'ie7'：IE7兼容模式，'ie8'：IE8兼容模式，'*'：IE9+兼容模式]
            keepBreaks: false, //类型：Boolean 默认：false [是否保留换行]
            keepSpecialComments: '*'
            //保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀，如果不加这个参数，有可能将会删除你的部分前缀
        }))
        .pipe(rev())
        .pipe(gulp.dest('./dist/css'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./json/css'));
});
gulp.task('minify-html', function() {
    var options = {
        collapseWhitespace: true,
        collapseBooleanAttributes: true,
        removeComments: true,
        removeEmptyAttributes: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
        minifyJS: true,
        minifyCSS: true
    };
    return gulp.src(['./src/*.html', './src/**/*.html', '!./src/ueditor/*.html', '!./src/ueditor/**/*.html', '!./src/ueditor/**/**/*.html'], { base: './src' })
        .pipe(htmlmin(options))
        .pipe(gulp.dest('./temp'));
});
gulp.task('rev-html', function() {
    return gulp.src(['./temp/*.html', '!./temp/index.html'], { base: './temp' })
        .pipe(rev())
        .pipe(gulp.dest('./dist'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./json'));
});
gulp.task('copy-index', function() {
    return gulp.src(['./temp/index.html'], { base: './temp' })
        .pipe(copy('./dist', {
            prefix: 1
        }));
});
gulp.task('copy-fonts',function(){
    return gulp.src(['./src/fonts/*.{eot,svg,ttf,woff}','./src/css/font/*.{eot,svg,ttf,woff}'],{base: './src'})
        .pipe(copy('./dist',{
            prefix: 1
        }));
});
gulp.task('copy-editor',  function() {
    return gulp.src(['./src/ueditor/*','./src/ueditor/**/*','./src/ueditor/**/**/*','./src/ueditor/**/**/**/*','./src/ueditor/**/**/**/**/*'],{base: './src'})
        .pipe(gulp.dest('./dist'))
});
// gulp.task('copy-editor',function(){
//   return gulp.src('./src/ueditor/*',{base: './src'})
//     .pipe(copy('./dist',{
//       prefix: 1
//     }));
// });
gulp.task('clean-temp', ['rev-html', 'copy-index'], function() {
    return gulp.src('./temp')
        .pipe(clean());
});
gulp.task('clean-json', function() {
    return gulp.src('./json')
        .pipe(clean());
});
gulp.task('img-minify', function() {
    return gulp.src(['./src/images/*.{png,jpg,gif,ico}','./src/images/**/*.{png,jpg,gif,ico}'])
        .pipe(imagemin({
            optimizationLevel: 6, //类型：Number  默认：3  取值范围：0-7（优化等级）
            progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
            interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
            multipass: true, //类型：Boolean 默认：false 多次优化svg直到完全优化
            use: [pngquant()]
        }))
        .pipe(rev())
        .pipe(gulp.dest('./dist/images'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./json/images'));
});
gulp.task('file-include', function() {
    return gulp.src(['./src/template/*.html', './src/template/**/*.html'], { base: './src/template' })
        .pipe(fileInclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(gulp.dest('./src'));
});
gulp.task('html-to', function() {
    return gulp.src(['./src/template/*.html','!./src/template/**/*.html'], { base: './src/**.html' })
        .pipe(gulp.dest('./src'));
});
gulp.task('del-widget',function(){
    return gulp.src('./src/widget')
        .pipe(clean());
});
gulp.task('build', function() {
    return gulp.src(['./json/**/*.json', './dist/*.html', './dist/**/*.css', './dist/**/*.js'])
        .pipe(revCollector({
            replaceReved: true
        }))
        .pipe(gulp.dest('./dist'));
});

// gulp.task('deploy', function () {
//     return gulp.src('./dist/*')
//         .pipe(sftp({
//             remotePath: '/home/wwwroot/h5.bravets.com/meitianhoutai', //部署到服务器的路径
//             host: '106.15.225.36', //ip地址
//             user: 'hongyangwu', //帐号
//             pass: '123456', //密码
//             port: 22 //端口
//         }));
// });
// gulp.task('deployP', function () {
//     return gulp.src('./dist/*')
//         .pipe(sftp({
//             remotePath: '/root/app/', //部署到服务器的路径
//             host: 'xx.xxx.xxx.xx', //ip地址
//             user: 'root', //帐号
//             pass: "******", //密码
//             port: 22 //端口
//         }));
// });

// 测试服务器参数
var devDemo = {
    remotePath: '/home/wwwroot/h5.bravets.com/qingchuangAdmin', //部署到服务器的路径
    host: '106.15.225.36', //ip地址
    user: 'root', //帐号
    pass: 'Bravets.com', //密码
    port: 22 //端口
};
// 正式服务器参数
var devProd = {
    remotePath: '/home/wwwroot/h5.bravets.com/qncyh-admin', //部署到服务器的路径
    host: '106.15.225.36', //ip地址
    user: 'root', //帐号
    pass: 'Bravets.com', //密码
    port: 22 //端口
};
// 部署到远程测试服务器
gulp.task('deploy', function () {
  return gulp.src(['./dist/*', './dist/**/*', './dist/**/**/*', './dist/**/**/**/*', './dist/**/**/**/**/*', './dist/**/**/**/**/**/*'])
    .pipe(sftp(devDemo));
});
// 部署到远程正式服务器
gulp.task('deployP', function () {
  return gulp.src(['./dist/*', './dist/**/*', './dist/**/**/*', './dist/**/**/**/*', './dist/**/**/**/**/*', './dist/**/**/**/**/**/*'])
    .pipe(sftp(devProd));
});